package com.android.mmchat.manager;

/**
 * 系统与服务器之间通信的唯一渠道
 * @author LJG
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetManagerApache {
	private Context c;
	static private NetManagerApache instance = null;

	static public NetManagerApache getInstance(Context c) {
		if (instance == null) {
			instance = new NetManagerApache();
			instance.c = c.getApplicationContext();
		}
		return instance;
	}

	private NetManagerApache() {

	}
	
	/**post提价一个xml字符串并获取结果，并将结果转化为字符串,参数无须编码*/
	public String doPostXmlAsString(String url,String xmlData) throws Exception{
		StringBuffer sb = new StringBuffer();
		HttpClient httpClient=null;
		InputStream in=null;
		BufferedReader reader=null;
		try {
			httpClient=getHttpClient();
			HttpPost httpPost=new HttpPost(url);
			
			StringEntity se = new StringEntity(xmlData,HTTP.UTF_8);
			se.setContentType("text/xml");  
			httpPost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
			httpPost.setEntity(se);  
			
			HttpResponse response = httpClient.execute(httpPost);
			/**编码*/
			String charset="utf-8";
			Header[] contentType=response.getHeaders("Content-Type");
			if(contentType!=null){
				for(Header h:contentType){
					String temp=h.getValue();
					if(temp!=null&&!temp.equals("")){
						String[] str=temp.split(";");
						if(str!=null){
							for(String s:str){
								if(s.trim().toLowerCase().startsWith("charset=")){
									charset=s.trim().toLowerCase().replace("charset=", "");
									break;
								}
							}//end for str
						}//end str!=null
					}
				}//end for contentType
			}//end contentType!=null
			/**返回类型，是否是gzip压缩流*/
			String contentEncoding=null;
			Header[] contentEncodings=response.getHeaders("Content-Encoding");
			if(contentEncodings!=null){
				for(Header h:contentEncodings){
					if(h.getValue()!=null&&!h.getValue().equals("")){
						contentEncoding=h.getValue();
					}
				}
			}//end contentEncodings!=null
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				in = entity.getContent();
				if(contentEncoding!=null&&contentEncoding.equals("gzip")){
					in=new GZIPInputStream(in);
				}
				reader = new BufferedReader(new InputStreamReader(in,charset));
				String line = "";
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
			}//end 			
		}catch (Exception e) {
			throw new Exception("Net Exception", e);
		}finally{
			if(reader!=null){reader.close();}
			if(in!=null){in.close();}
			if(httpClient!=null){httpClient.getConnectionManager().shutdown();}
		}
		return sb.toString();
	}//end doPostAsString
	
	/**post方法获取结果，并将结果转化为字符串,参数无须编码*/
	public InputStream doPostAsInputstream(String url,Hashtable<String, String> tableData) throws Exception{
		HttpClient httpClient=null;
		InputStream in=null;
		try {
			httpClient=getHttpClient();
			HttpPost httpPost=new HttpPost(url);
			List<NameValuePair> nvps=new ArrayList<NameValuePair>();  
			if(tableData!=null){
				//需要通过POST提交的参数  
				Enumeration<String> enu = tableData.keys();
				String item = "";
				while (enu.hasMoreElements()) {
					item = enu.nextElement();
					nvps.add(new BasicNameValuePair(item, tableData.get(item)));  
				}
			}//end tableData!=null
			httpPost.setEntity(new UrlEncodedFormEntity(nvps,"utf-8")); 
			HttpResponse response = httpClient.execute(httpPost);
			/**返回类型，是否是gzip压缩流*/
			String contentEncoding=null;
			Header[] contentEncodings=response.getHeaders("Content-Encoding");
			if(contentEncodings!=null){
				for(Header h:contentEncodings){
					if(h.getValue()!=null&&!h.getValue().equals("")){
						contentEncoding=h.getValue();
					}
				}
			}//end contentEncodings!=null
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				in = entity.getContent();
				if(contentEncoding!=null&&contentEncoding.equals("gzip")){
					in=new GZIPInputStream(in);
				}
			}//end 			
		}catch (Exception e) {
			if(in!=null){in.close();}
			if(httpClient!=null){httpClient.getConnectionManager().shutdown();}
			throw new Exception("Net Exception", e);
		}
		return in;
	}//end doPostAsString
	
	/**post方法获取结果，并将结果转化为字符串,参数无须编码*/
	public String doPostAsString(String url,Hashtable<String, String> tableData) throws Exception{
		StringBuffer sb = new StringBuffer();
		HttpClient httpClient=null;
		InputStream in=null;
		BufferedReader reader=null;
		try {
			httpClient=getHttpClient();
			HttpPost httpPost=new HttpPost(url);
			List<NameValuePair> nvps=new ArrayList<NameValuePair>();  
			if(tableData!=null){
				//需要通过POST提交的参数  
				Enumeration<String> enu = tableData.keys();
				String item = "";
				while (enu.hasMoreElements()) {
					item = enu.nextElement();
					nvps.add(new BasicNameValuePair(item, tableData.get(item)));  
				}
			}//end tableData!=null
			httpPost.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));  
			HttpResponse response = httpClient.execute(httpPost);
			/**编码*/
			String charset="utf-8";
			Header[] contentType=response.getHeaders("Content-Type");
			if(contentType!=null){
				for(Header h:contentType){
					String temp=h.getValue();
					if(temp!=null&&!temp.equals("")){
						String[] str=temp.split(";");
						if(str!=null){
							for(String s:str){
								if(s.trim().toLowerCase().startsWith("charset=")){
									charset=s.trim().toLowerCase().replace("charset=", "");
									break;
								}
							}//end for str
						}//end str!=null
					}
				}//end for contentType
			}//end contentType!=null
			/**返回类型，是否是gzip压缩流*/
			String contentEncoding=null;
			Header[] contentEncodings=response.getHeaders("Content-Encoding");
			if(contentEncodings!=null){
				for(Header h:contentEncodings){
					if(h.getValue()!=null&&!h.getValue().equals("")){
						contentEncoding=h.getValue();
					}
				}
			}//end contentEncodings!=null
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				in = entity.getContent();
				if(contentEncoding!=null&&contentEncoding.equals("gzip")){
					in=new GZIPInputStream(in);
				}
				reader = new BufferedReader(new InputStreamReader(in,charset));
				String line = "";
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
			}//end 			
		}catch (Exception e) {
			throw new Exception("Net Exception", e);
		}finally{
			if(reader!=null){reader.close();}
			if(in!=null){in.close();}
			if(httpClient!=null){httpClient.getConnectionManager().shutdown();}
		}
		return sb.toString();
	}//end doPostAsString
	
	/**get方法获取结果，并返回输入流,参数无须编码*/
	public InputStream doGetAsInputstream(String url,Hashtable<String, String> tableData) throws Exception{
		HttpClient httpClient=null;
		InputStream in=null;
		try {
			httpClient=getHttpClient();
			String getUrl=url;
			if(tableData!=null){
				StringBuffer sb=new StringBuffer();
				Enumeration<String> enu = tableData.keys();
				String item = "";
				while (enu.hasMoreElements()) {
					item = enu.nextElement();
					sb.append("&"+item+"="+URLEncoder.encode(tableData.get(item), "utf-8")); 
				}
				if(url.contains("?")){
					getUrl=url+sb.toString();
				}else{
					getUrl=url+"?"+sb.toString();
				}
			}//end tableData!=null
			HttpGet httpGet = new HttpGet(getUrl);
			HttpResponse response = httpClient.execute(httpGet);
			/**返回类型，是否是gzip压缩流*/
			String contentEncoding=null;
			Header[] contentEncodings=response.getHeaders("Content-Encoding");
			if(contentEncodings!=null){
				for(Header h:contentEncodings){
					if(h.getValue()!=null&&!h.getValue().equals("")){
						contentEncoding=h.getValue();
					}
				}
			}//end contentEncodings!=null
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				in = entity.getContent();
				if(contentEncoding!=null&&contentEncoding.equals("gzip")){
					in=new GZIPInputStream(in);
				}
			}//end 			
		}catch (Exception e) {
			if(in!=null){in.close();}
			if(httpClient!=null){httpClient.getConnectionManager().shutdown();}
			throw new Exception("Net Exception", e);
		}
		return in;
	}//end doGetAsInputstream
	
	/**get方法获取结果，并将结果转化为字符串,参数无须编码*/
	public String doGetAsString(String url,Hashtable<String, String> tableData) throws Exception {
		StringBuffer sb = new StringBuffer();
		HttpClient httpClient=null;
		InputStream in=null;
		BufferedReader reader=null;
		try {
			httpClient=getHttpClient();
			String getUrl=url;
			if(tableData!=null){
				StringBuffer sb2=new StringBuffer();
				Enumeration<String> enu = tableData.keys();
				String item = "";
				while (enu.hasMoreElements()) {
					item = enu.nextElement();
					sb2.append("&"+item+"="+URLEncoder.encode(tableData.get(item), "utf-8")); 
				}
				if(url.contains("?")){
					getUrl=url+sb2.toString();
				}else{
					getUrl=url+"?"+sb2.toString();
				}
			}//end tableData!=null
			HttpGet httpGet = new HttpGet(getUrl);
			HttpResponse response = httpClient.execute(httpGet);
			/**编码*/
			String charset="utf-8";
			Header[] contentType=response.getHeaders("Content-Type");
			if(contentType!=null){
				for(Header h:contentType){
					String temp=h.getValue();
					if(temp!=null&&!temp.equals("")){
						String[] str=temp.split(";");
						if(str!=null){
							for(String s:str){
								if(s.trim().toLowerCase().startsWith("charset=")){
									charset=s.trim().toLowerCase().replace("charset=", "");
									break;
								}
							}//end for str
						}//end str!=null
					}
				}//end for contentType
			}//end contentType!=null
			/**返回类型，是否是gzip压缩流*/
			String contentEncoding=null;
			Header[] contentEncodings=response.getHeaders("Content-Encoding");
			if(contentEncodings!=null){
				for(Header h:contentEncodings){
					if(h.getValue()!=null&&!h.getValue().equals("")){
						contentEncoding=h.getValue();
					}
				}
			}//end contentEncodings!=null
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				in = entity.getContent();
				if(contentEncoding!=null&&contentEncoding.equals("gzip")){
					in=new GZIPInputStream(in);
				}
				reader = new BufferedReader(new InputStreamReader(in,charset));
				String line = "";
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
			}//end 			
		}catch (Exception e) {
			throw new Exception("Net Exception", e);
		}finally{
			if(reader!=null){reader.close();}
			if(in!=null){in.close();}
			if(httpClient!=null){httpClient.getConnectionManager().shutdown();}
		}
		return sb.toString();
	}//end dogetAsString
	/**获取httpClient*/
	public HttpClient getHttpClient() throws Exception {
		HttpClient httpClient = new DefaultHttpClient();
		if (!isWiFiActive()) {
			String proxyHost = android.net.Proxy.getDefaultHost();
			if (proxyHost != null && !proxyHost.equals("")) {
				HttpHost proxy = new HttpHost(proxyHost, android.net.Proxy.getDefaultPort());
				httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
			}
		}
		HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 20 * 1000);
		HttpConnectionParams.setSoTimeout(httpClient.getParams(),20 * 1000);
		return httpClient;
	}//end getHttpClient
	/**判断wifi是否可用*/
	private boolean isWiFiActive() {
		ConnectivityManager connectivity = (ConnectivityManager) c
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (info != null && info.getTypeName().equals("WIFI")) {
				return true;
			}
		}
		return false;
	}

	/** 判断是否有可用网络*/
	public static boolean isNetworkAvailable(Context ctx) {
		ConnectivityManager connectivity = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}// end isNetworkAvailable
}
